using UnityEngine;
using System.Collections;

public static class Controller{
	
	private static ArrayList unassignedJobs;
	private static ArrayList idlingRobots;
	private static ArrayList unusedTools;
	
	// Use this for initialization
	public static void Start () {
		unassignedJobs = null;
		idlingRobots = null;
		unassignedJobs = new ArrayList();
		idlingRobots = new ArrayList();
		unusedTools = new ArrayList();
	}
	
	// Update is called once per frame
	public static void Update () {
		if ((int)(idlingRobots.Count) != 0){
			if (unassignedJobs.Count != 0){
				Robot bestRobot = (Robot)(idlingRobots[0]);
				Job jobToBeAssigned = (Job) (unassignedJobs[0]);
				int bestCost = getCostOf(bestRobot, jobToBeAssigned);;
				
				foreach(Robot rob in idlingRobots){
					if ((getCostOf(rob, jobToBeAssigned)) < bestCost){
						bestCost = getCostOf(rob, jobToBeAssigned);
						bestRobot = rob;
					}
				}
				
				bestRobot.assignJob(jobToBeAssigned);
				unassignedJobs.Remove(jobToBeAssigned);
				idlingRobots.Remove(bestRobot);
			}
		}
	}
	
	
	public static void addJob(Job j){
		unassignedJobs.Add(j);
	}
	
	public static void addRobot(Robot r){
		idlingRobots.Add (r);
	}
	
	public static void finishedJob(Robot r, Job j){
		try {
			idlingRobots.Add(r);
		} catch {
			
		}
	}
	
	public static void removeRobot(Robot robot){
		idlingRobots.Remove(robot);
	}
	
	public static ArrayList getUnusedTools(){
		return unusedTools;
	}
	
	public static void addUnusedTool(Tool t){
		unusedTools.Add(t);
	}
	
	public static void removeTool(Tool t){
		unusedTools.Remove(t);
	}
	
	public static int getCostOf(Robot robot, Job job){
		int cost = 0;
		Point robotPoint = robot.getPostion();
		cost += Mathf.Abs(robotPoint.x - job.x);
		cost += Mathf.Abs(robotPoint.y - job.y);
		cost += Mathf.Abs(robotPoint.z - job.z);
		
		if (job.jobType == 2){
			cost -= (int)(3 * (robot.rateOfConstruction));
		} else if (job.jobType == 3){
			cost -= (int)(3 * (robot.rateOfDeconstruction));
		} else if (job.jobType == 6){
			cost -= (int)(3 * (robot.rateOfMining));
		}
		
		return cost;
	}
	
	public static void removeJob(Job j){
		unassignedJobs.Remove(j);
	}
}
